<template>
  <el-dialog
    v-model="dialogVisible"
    title="Document Questions"
    width="70%"
    :before-close="handleClose"
    class="questions-dialog"
  >
    <div class="dialog-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else-if="!questions || questions.length === 0" class="empty-questions">
        <el-empty description="No questions found for this document">
          <template #description>
            <p>{{ emptyMessage }}</p>
          </template>
          <el-button type="primary" @click="parseDocument" :loading="parsing">
            Parse Document
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="questions-container">
        <div class="questions-header">
          <div class="document-info">
            <h3>{{ document?.title }}</h3>
            <el-tag size="small" type="success">{{ questions.length }} Questions</el-tag>
          </div>
          
          <div class="questions-actions">
            <el-button type="primary" @click="createExercise" :disabled="!canCreateExercise">
              <el-icon><Plus /></el-icon>
              Create Exercise
            </el-button>
            <el-button @click="exportQuestions" :disabled="!canExport">
              <el-icon><Download /></el-icon>
              Export
            </el-button>
          </div>
        </div>
        
        <el-table :data="questions" style="width: 100%" border>
          <el-table-column type="index" width="50" />
          
          <el-table-column prop="text" label="Question" min-width="300">
            <template #default="{ row }">
              <div class="question-text">{{ row.text }}</div>
            </template>
          </el-table-column>
          
          <el-table-column prop="type" label="Type" width="120">
            <template #default="{ row }">
              <el-tag size="small" :type="getQuestionTypeColor(row.type)">
                {{ formatQuestionType(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="difficulty" label="Difficulty" width="120">
            <template #default="{ row }">
              <el-rate
                v-model="row.difficulty"
                disabled
                text-color="#ff9900"
                :max="3"
                :colors="difficultyColors"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="Actions" width="120" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="editQuestion(row)"
                circle
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="deleteQuestion(row)"
                circle
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">Close</el-button>
        <el-button type="primary" @click="refreshQuestions" :loading="loading">
          <el-icon><Refresh /></el-icon>
          Refresh
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { Plus, Download, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'QuestionsDialog',
  
  components: {
    Plus,
    Download,
    Edit,
    Delete,
    Refresh
  },
  
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    document: {
      type: Object,
      default: null
    }
  },
  
  emits: ['update:modelValue', 'refresh', 'parse', 'create-exercise'],
  
  setup(props, { emit }) {
    const loading = ref(false)
    const parsing = ref(false)
    const questions = ref([])
    
    const dialogVisible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    })
    
    const difficultyColors = ['#99A9BF', '#F7BA2A', '#FF9900']
    
    const emptyMessage = computed(() => {
      if (!props.document) return 'No document selected'
      if (props.document.parser_status === 'processing') return 'Document is currently being processed'
      if (props.document.parser_status === 'failed') return 'Document parsing failed'
      return 'No questions have been extracted from this document yet'
    })
    
    const canCreateExercise = computed(() => {
      return questions.value && questions.value.length > 0
    })
    
    const canExport = computed(() => {
      return questions.value && questions.value.length > 0
    })
    
    const handleClose = () => {
      dialogVisible.value = false
    }
    
    const fetchQuestions = async () => {
      if (!props.document) return
      
      loading.value = true
      
      try {
        // In a real application, you would fetch questions from an API
        // const response = await api.getDocumentQuestions(props.document.id)
        // questions.value = response.data
        
        // Mock data for demonstration
        setTimeout(() => {
          if (props.document.parser_status === 'completed') {
            questions.value = [
              {
                id: 1,
                text: 'What is the main purpose of the document?',
                type: 'open_ended',
                difficulty: 2
              },
              {
                id: 2,
                text: 'Which of the following statements is true according to the document?',
                type: 'multiple_choice',
                difficulty: 1,
                options: [
                  'Option A',
                  'Option B',
                  'Option C',
                  'Option D'
                ],
                correctAnswer: 1
              },
              {
                id: 3,
                text: 'Explain the relationship between concepts X and Y mentioned in section 3.',
                type: 'open_ended',
                difficulty: 3
              }
            ]
          } else {
            questions.value = []
          }
          
          loading.value = false
        }, 1000)
      } catch (error) {
        console.error('Error fetching questions:', error)
        ElMessage.error('Failed to load questions')
        loading.value = false
      }
    }
    
    const refreshQuestions = () => {
      fetchQuestions()
    }
    
    const parseDocument = async () => {
      if (!props.document) return
      
      parsing.value = true
      
      try {
        // In a real application, you would call an API to parse the document
        // await api.parseDocument(props.document.id)
        
        // Emit event to parent component to handle parsing
        emit('parse', props.document)
        
        // Mock successful parsing
        setTimeout(() => {
          ElMessage.success('Document parsing initiated')
          parsing.value = false
        }, 1000)
      } catch (error) {
        console.error('Error parsing document:', error)
        ElMessage.error('Failed to parse document')
        parsing.value = false
      }
    }
    
    const createExercise = () => {
      if (!canCreateExercise.value) return
      
      // Emit event to parent component to handle exercise creation
      emit('create-exercise', {
        document: props.document,
        questions: questions.value
      })
      
      // Close dialog
      dialogVisible.value = false
    }
    
    const exportQuestions = () => {
      if (!canExport.value) return
      
      // In a real application, you would implement export functionality
      ElMessage.success('Questions exported successfully')
    }
    
    const editQuestion = (question) => {
      // In a real application, you would implement question editing
      ElMessage.info(`Editing question: ${question.id}`)
    }
    
    const deleteQuestion = (question) => {
      ElMessageBox.confirm(
        'Are you sure you want to delete this question?',
        'Warning',
        {
          confirmButtonText: 'Delete',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      )
        .then(() => {
          // In a real application, you would call an API to delete the question
          // await api.deleteQuestion(question.id)
          
          // Remove question from local state
          questions.value = questions.value.filter(q => q.id !== question.id)
          
          ElMessage.success('Question deleted successfully')
        })
        .catch(() => {
          // User cancelled
        })
    }
    
    const getQuestionTypeColor = (type) => {
      switch (type) {
        case 'multiple_choice':
          return 'success'
        case 'true_false':
          return 'warning'
        case 'open_ended':
          return 'info'
        default:
          return 'default'
      }
    }
    
    const formatQuestionType = (type) => {
      switch (type) {
        case 'multiple_choice':
          return 'Multiple Choice'
        case 'true_false':
          return 'True/False'
        case 'open_ended':
          return 'Open Ended'
        default:
          return type
      }
    }
    
    // Watch for changes to the document prop
    watch(() => props.document, (newDocument) => {
      if (newDocument && dialogVisible.value) {
        fetchQuestions()
      }
    })
    
    // Watch for dialog visibility
    watch(() => dialogVisible.value, (isVisible) => {
      if (isVisible && props.document) {
        fetchQuestions()
      }
    })
    
    return {
      dialogVisible,
      loading,
      parsing,
      questions,
      difficultyColors,
      emptyMessage,
      canCreateExercise,
      canExport,
      handleClose,
      refreshQuestions,
      parseDocument,
      createExercise,
      exportQuestions,
      editQuestion,
      deleteQuestion,
      getQuestionTypeColor,
      formatQuestionType
    }
  }
}
</script>

<style scoped>
.questions-dialog {
  max-width: 1200px;
}

.dialog-content {
  min-height: 300px;
}

.loading-container {
  padding: 20px;
}

.empty-questions {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.questions-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.questions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.document-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.document-info h3 {
  margin: 0;
  font-size: 18px;
}

.questions-actions {
  display: flex;
  gap: 10px;
}

.question-text {
  white-space: normal;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
</style> 